package net.expectx.gw.controller;


import com.google.code.kaptcha.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.expectx.common.base.BaseResultConstants;
import net.expectx.gw.bean.PermissionUser;
import net.expectx.gw.bean.SystemSetting;
import net.expectx.gw.service.PermissionUserService;
import net.expectx.gw.service.SystemSettingService;
import net.expectx.gw.util.AdminResult;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 单点登录管理
 * @author jianhun
 * @date 2018/5/17
 */
@Controller
@RequestMapping("/sso")
@Api(value = "单点登录管理", description = "单点登录管理")
public class SsoController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SsoController.class);
    /**
     * 全局会话key
     */
    private final static String TITIFOOTBALL_UPMS_SERVER_SESSION_ID = "titifootball-upms-server-session-id";
    /**
     * 全局会话key列表
     */
    private final static String TITIFOOTBALL_UPMS_SERVER_SESSION_IDS = "titifootball-upms-server-session-ids";
    /**
     * code key
     */
    private final static String TITIFOOTBALL_UPMS_SERVER_CODE = "titifootball-upms-server-code";

    @Autowired
    PermissionUserService permissionUserService;
    @Autowired
    SystemSettingService systemSettingService;

    @ApiOperation(value = "登录")
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request) {

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        List<SystemSetting>systemSettings=systemSettingService.findByAttr("is_deleted=0",null);
        session.setAttribute("systemSettings",systemSettings);
        PermissionUser permissionUser = (PermissionUser) session.getAttribute("permissionUser");
        if (null!=permissionUser) {
            // 回跳
            String backurl = request.getParameter("backurl");
            String username = (String) subject.getPrincipal();
            if (StringUtils.isBlank(backurl)) {
                backurl = "/";
            } else {
                String str = "?";
            }
            LOGGER.debug("认证中心帐号通过，带code回跳：{}", backurl);
            StringBuffer sb = new StringBuffer("redirect:").append(backurl);
            return sb.toString();
        }

        return "login";

    }

    @ApiOperation(value = "登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");
        String vercode = request.getParameter("vercode");

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String sessionId = session.getId().toString();
        PermissionUser permissionUser=(PermissionUser) session.getAttribute("permissionUser");
        //String hasCode = RedisUtil.get(TITIFOOTBALL_UPMS_SERVER_SESSION_ID + "_" + sessionId);
        // code校验值
        if (null==permissionUser) {
            if (vercode.toLowerCase().equals(session.getAttribute(Constants.KAPTCHA_SESSION_KEY).toString().toLowerCase())){
                // 使用shiro认证
                UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
                try {
                    if (StringUtils.isNotEmpty(rememberMe)) {
                        usernamePasswordToken.setRememberMe(true);
                    } else {
                        usernamePasswordToken.setRememberMe(false);
                    }

                    subject.login(usernamePasswordToken);
                } catch (UnknownAccountException e) {
                    return new AdminResult(false,BaseResultConstants.FAILED, "帐号不存在！");
                } catch (IncorrectCredentialsException e) {
                    return new AdminResult(false,BaseResultConstants.FAILED, "密码错误！");
                } catch (LockedAccountException e) {
                    return new AdminResult(false,BaseResultConstants.FAILED, "帐号已锁定！");
                }
            }else{
                return new AdminResult(false, BaseResultConstants.FAILED, "验证码错误！");
            }



        }

        // 回跳登录前地址
        String backurl = request.getParameter("backurl");
        if (StringUtils.isBlank(backurl)) {

        }

        return new AdminResult(true,BaseResultConstants.SUCCESS, backurl);
    }



    @ApiOperation(value = "退出登录")
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request) {

        // shiro退出登录
        SecurityUtils.getSubject().logout();
        // 跳回原地址
        String redirectUrl = request.getHeader("Referer");
        if (null == redirectUrl) {
            redirectUrl = "/";
        }

        StringBuffer sb = new StringBuffer("redirect:").append(redirectUrl);
        return sb.toString();

    }

}
